package classes
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.FileListEvent;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.filesystem.File;
	import flash.geom.Matrix;
	import flash.net.URLRequest;
	
	import mx.controls.Alert;
	import mx.utils.ObjectProxy;
	
	import qs.controls.SuperImage;
			
	
	public class PhotoLoader extends EventDispatcher
	{
		private var originalBitmapData:BitmapData;
		private var originalFile:File;
		private var p : PhotoObject = new PhotoObject;
		private var b:Boolean = false;		
		private var n:Number = 0;
		private static const MAX_WIDTH:uint = 2880;
		private static var MAX_HEIGHT:uint = 2880;
		
		[Bindable] public var photoObject:ObjectProxy;
		public var loadStatus:ObjectProxy;
		public var loader:Loader;
		public var percentComplete:ObjectProxy;
		public var photoCollection:PhotoCollection;
		private var _percent:Number;
		public function PhotoLoader()
		{		
			super(this);
			photoObject = new ObjectProxy(p);
			loadStatus = new ObjectProxy(b);
			loadStatus.type = Boolean;
			loadStatus.object = false;	
			
			percentComplete = new ObjectProxy(n);
			percentComplete.type = Number;
			percentComplete.object = 0;
			
			photoCollection = new PhotoCollection();
			photoCollection.activity = "Caesr Photo";
			photoCollection.title = "Caesaro";
			photoCollection.date = "";		
			_percent = new Number(0); 	
		}
		
		public function photoObjectChangeHandler(event:Event):void
		{
			trace("### PHOTO OBJECT PROXY CHANGE IN PHOTOLOADER :###\n"+event.target.title);
		}
		public function get percent():Number
		{
			return _percent;
		}
		public function loadImages(files:FileListEvent):void
		{			
			trace("LOADING FILES");
			for each (var file:File in files.files)
			{
				trace("LOAD IMAGE: "+file.name);
				loadImage(file);				
			}										
	}				
		public function loadImage(file:File):void
		{											
			trace("<<< loadImage( "+file.name+" ) >>>");
			originalFile = file;
			
		 	var request:URLRequest = new URLRequest(file.url);		 
		    loader = new Loader();
		    configureListeners(loader);
		    loader.load(request);			    			   	       			 
		}
		
		private function configureListeners(dispatcher:Loader):Boolean {
			try{
				trace("<<< configureListeners( "+dispatcher+" ) >>>");
	            dispatcher.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
	            dispatcher.contentLoaderInfo.addEventListener(Event.OPEN, openHandler);
	            dispatcher.contentLoaderInfo.addEventListener(Event.CLOSE, closeHandler);
	            dispatcher.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
	            dispatcher.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
	            dispatcher.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
	            dispatcher.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			} catch (e:Error) {
				trace(e.message+" ||| "+e.getStackTrace())
				return false;
			} finally {
				return true;
			}
		}

		private function completeHandler(event:Event):void
		{
			try
			{									
				trace(" ### imageCompleteHandler( " + event.currentTarget.valueOf() + " ) ###");

			 	var loader:Loader = Loader(event.target.loader);
	            var bitMap:Bitmap = Bitmap(loader.content);
				
				var bitmapData:BitmapData = bitMap.bitmapData;			
			 	
			 	var originalWidth:Number = bitmapData.width;
			 	var originalHeight:Number = bitmapData.height;
			 	
			 	var newWidth:Number = originalWidth;
			 	var newHeight:Number = originalHeight;
			 	var image:SuperImage = new SuperImage();	
			 	var m:Matrix = new Matrix();
			 			
			 	var scaleX:Number = 1;
			 	var scaleY:Number = 1;
			 
			 	if (originalWidth > MAX_WIDTH || originalHeight > MAX_HEIGHT)
			 	{
			  		var sx:uint =  MAX_WIDTH / originalWidth;
			  		var sy:uint = MAX_HEIGHT / originalHeight;
			  		var scale:Number = Math.min(sx, sy);
			  		newWidth = originalWidth * scale;
			  		newHeight = originalHeight * scale;	
			  	}
			 	m.scale(scale, scale);
			 	photoObject._bitmapData = new BitmapData(newWidth, newHeight, false); 		 				
			 	photoObject._bitmapData.draw(bitmapData, m);
			 	photoObject._bitmap =bitMap;
			 		
			 	photoObject.title = originalFile.name;
			 	
			 	photoObject.url = originalFile.url;
			 	photoObject.addTransform(m);
			 	
			 	photoObject._image = new SuperImage();
			 	photoObject._image.source = photoObject.bitmapData
				
				if (photoCollection.contains(photoObject)){
					trace ("!#!#!#! Bestand "+photoObject.title +" bestaat al");
				}
				else {
					photoCollection.addItem(photoObject);
					trace ("!@!@!@! Bestand "+photoObject.title +" toegevoegd op "+(photoObject.index).toString())+" "+photoObject.index;					
				}													
			}
			catch (e:ArgumentError) 
			{
				photoObject.url = "assets/missing.jpg";
				trace ("error in completeHandler = "+e.message +" Name "+ e.name + e.getStackTrace());
			} 
			
			
		}
		private function ioErrorHandler(event:IOErrorEvent):void
		{
			trace("Fout");
			 Alert.show(event.text,"Could not load images.");
		}		
		
		public function loadComplete():Boolean
		{
			return loadStatus as Boolean;
		}

		public function getPhotoCollection():PhotoCollection
		{
			var value : PhotoCollection = new PhotoCollection ()
			
			if (loadStatus){
				value = photoCollection
				trace("photoCollection returned to main"+photoCollection[0].title);
			
			}
			else  {
				value = null;
				trace("Loading is not finished");
			}
			return value;
		}

        private function openHandler(event:Event):void {
            trace ("Image Loader openHandler: " + event);
            loadStatus.object = false;
           // Application.application.progress.visible = true;
        }
         private function closeHandler(event:Event):void {
            trace ("Image Loader closeHandler: " + event.target.valueOf());
            loadStatus.object = true;
            
        }
        private function progressHandler(event:ProgressEvent):void {
        	_percent = Math.round((event.bytesLoaded * 100)/event.bytesTotal)
        	dispatchEvent(new Event("progress"));
        	//percentComplete.object = Math.round((event.bytesLoaded * 100)/event.bytesTotal);
            // Application.application.progress.setProgress(Math.round((event.bytesLoaded * 100)/event.bytesTotal),100);
            if (event.bytesLoaded == event.bytesTotal)
            {
            	dispatchEvent(new Event("complete"));
            	//Application.application.progress.visible = false;
            }
            trace ("Image Loader progressHandler "+percentComplete.object+"% loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
        }

        private function securityErrorHandler(event:SecurityErrorEvent):void {
            trace ("Image Loader securityErrorHandler: " + event);
        }

        private function httpStatusHandler(event:HTTPStatusEvent):void {
            trace ("Image Loader httpStatusHandler: " + event);
        }

	}
}